package com.panwenliang2008.eatwhat.workers

import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import com.panwenliang2008.eatwhat.data.database.AppDatabase
import com.panwenliang2008.eatwhat.data.entity.Food
import com.panwenliang2008.eatwhat.utilities.FOOD_DATA_FILENAME_EN
import com.panwenliang2008.eatwhat.utilities.FOOD_DATA_FILENAME_JA
import com.panwenliang2008.eatwhat.utilities.FOOD_DATA_FILENAME_ZH
import kotlinx.coroutines.coroutineScope
import java.util.*

class SeedDatabaseWorker(
    context: Context,
    workerParams: WorkerParameters
) : CoroutineWorker(context, workerParams) {
    override suspend fun doWork(): Result = coroutineScope {
        try {

            val foodsJsonFilename = when(Locale.getDefault().language) {
                "en" -> FOOD_DATA_FILENAME_EN
                "ja" -> FOOD_DATA_FILENAME_JA
                "zh" -> FOOD_DATA_FILENAME_ZH
                else -> FOOD_DATA_FILENAME_EN
            }


            applicationContext.assets.open(foodsJsonFilename).use { inputStream ->
                JsonReader(inputStream.reader()).use { jsonReader ->
                    val plantType = object : TypeToken<List<Food>>() {}.type
                    val plantList: List<Food> = Gson().fromJson(jsonReader, plantType)

                    val database = AppDatabase.getInstance(applicationContext)
                    database.foodDao().insertAll(plantList)

                    Result.success()
                }
            }

        } catch (ex: Exception) {
            //log
            Result.failure()
        }
    }

}